from rest_framework import serializers
from comment.models import Comment
from django.utils import timezone
from user_info.serializers import UserDescSerializer


class CommentChildrenSerializer(serializers.ModelSerializer):
  url = serializers.HyperlinkedIdentityField(view_name='comment-detail')
  author = UserDescSerializer(read_only=True)

  class Meta:
    model = Comment
    # 定义不需要的字段
    exclude = [
      'parent',
      'article',
    ]

class CommentSerializer(serializers.ModelSerializer):
  # HyperlinkedIdentityField 用于对当前模型自身
  url = serializers.HyperlinkedIdentityField(view_name='comment-detail')
  author = UserDescSerializer(read_only=True)

  # HyperlinkedRelatedField 用于对外键关系
  article = serializers.HyperlinkedRelatedField(view_name='article-detail', read_only=True)
  article_id = serializers.IntegerField(write_only=True, allow_null=False, required=True)

  parent = CommentChildrenSerializer(read_only=True)
  parent_id = serializers.IntegerField(write_only=True, allow_null=True, required=False)

  # 更新评论时忽略掉 parent_id 参数
  def update(self, instance, validated_data):
    validated_data.pop('parent_id', None)
    validated_data['modified']=timezone.now()
    return super().update(instance, validated_data)

  class Meta:
    model = Comment
    fields = '__all__'
    extra_kwargs = {'created': {'read_only': True}}
